<?php

/**
 * This is the model class for table "topic".
 *
 * The followings are the available columns in table 'topic':
 * @property string $id
 * @property string $name
 * @property integer $time_create
 * @property integer $time_update
 * @property string $url
 * @property string $desc
 * @property string $color
 *
 *
 * @property Series[] $serieses
 * @property Task[] $tasks
 */
class Topic extends CActiveRecord
{


    public $time_begin;
    public $time_end;
    public $searchKey;
    public $pic;
    public $sid;
    public $extIds;
    public $taskId;

    private $aids;
    public $sids;

    protected function beforeSave()
    {
        //save image
        if (empty($this->pic)) {
            $image = CUploadedFile::getInstance($this, 'pic');
            if (!empty($image)) {
                $filename = md5($this->name) . '.' . $image->extensionName;
                if (!is_dir('./upload/')) {
                    mkdir('./upload/');
                }
                if ($image->saveAs("./upload/" . $filename)) {
                    $this->url = "/upload/" . $filename;
                }
            }

        }
        return parent::beforeSave(); // TODO: Change the autogenerated stub
    }

    public function afterSave($event)
    {
        $this->updateLink('update');
        parent::afterSave($event); // TODO: Change the autogenerated stub
    }

    protected function afterFind()
    {
        $this->sids = array_map(function (SeriesTopic $series_topic) {
            return $series_topic->sid;
        }, $this->series_topic);
        parent::beforeFind(); // TODO: Change the autogenerated stub
    }

    public function setAids($Aids)
    {
        $this->aids = $Aids;
    }

    public function getAids()
    {
        if (empty($this->aids)) {
            $this->aids = array_map(function ($task) {
                return $task->id;
            }, $this->tasks);
        }
        return $this->aids;
    }

    private static $_options;

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'topic';
    }

    public function onAfterDelete($event)
    {
        $this->updateLink('delete');
        parent::onAfterDelete($event); // TODO: Change the autogenerated stub
    }


    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('time_create, time_update', 'numerical', 'integerOnly' => true),
            array('name, color', 'length', 'max' => 11),
            array('desc', 'length', 'max' => 128),
            array('id, name, time_create, time_update, url, desc, color,sid,extIds,taskId', 'safe', 'on' => 'search'),
            array('name', 'required'),
            array('name', 'unique', 'on' => 'insert'),
            array('pic',
                'file',
                'allowEmpty' => true,
                'types' => 'png',
                'maxSize' => 1024 * 1024 * 1,
                'tooLarge' => '头像最大不超过1MB，请重新上传!',),
            array('time_begin, time_end,sids,searchKey,pic', 'safe'),
            array(
                'time_update',
                'default',
                'value' => time(),
                'setOnEmpty' => false,
                'on' => 'update'
            ),
            array(
                'time_create, time_update',
                'default',
                'value' => time(),
                'setOnEmpty' => false,
                'on' => 'insert'
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array(
            'serieses' => array(self::MANY_MANY, 'Series', 'series_topic(tid, sid)', 'order' => 'weight desc'),
            'series_topic' => array(self::HAS_MANY, 'SeriesTopic', ['tid' => 'id']),
            'topicExts' => array(self::HAS_MANY, 'TopicExt', ['tid' => 'id'],'index'=>'weight'));
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => '主题名称',
            'time_create' => 'Time Create',
            'time_update' => 'Time Update',
            'url' => '图标',
            'desc' => '主题简介',
            'color' => '主题颜色',
            'sids' => '关联分类',
            'aids' => '关联视频任务',
            'pic' => '主题图标',
        );
    }


    public static function getOptions($attribute, $options = array())
    {
        if (!isset(self::$_options[$attribute])) {
            $opts = [];
            switch ($attribute) {
                case 'topics':
                    $topics = Topic::model()->findAll();
                    foreach ($topics as $topic) {
                        $opts[$topic->id] = $topic->name;
                    }
                    break;
            }
            self::$_options[$attribute] = $opts;
        }
        if (is_array($options) && !empty($options)) {
            foreach (self::$_options[$attribute] as $k => $v) {
                $options[$k] = $v;
            }
        } else {
            $options = self::$_options[$attribute];
        }
        return $options;
    }


    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function searchByKey()
    {
// @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;
        if (!isset($_GET['Topic_sort'])) {
            $criteria->order = 't.id DESC';
        }

        if (!empty($ts_begin = strtotime($this->time_begin))) {
            $criteria->addCondition('`time_create` >= ' . $ts_begin);
        }
        if (!empty($ts_end = strtotime($this->time_end))) {
            $criteria->addCondition('`time_create` <= ' . $ts_end);
        }
        if (!empty($this->sid)) {
            $ids = array_map(function ($seriestopic) {
                return $seriestopic->tid;
            }, SeriesTopic::model()->findAllByAttributes(['sid' => $this->sid,]));

            $criteria->addInCondition('id', $ids);
        }
        if ($this->searchKey !== '') {
            $criteria->compare('name', $this->searchKey, true);
            $criteria->compare('url', $this->searchKey, true);
            $criteria->compare('`desc`', $this->searchKey, true);
            $criteria->compare('color', $this->searchKey, true);
        }

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Topic the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function updateExt($type)
    {
        if ($this->extIds) {
            $criteria = new CDbCriteria();
            $criteria->addColumnCondition(['tid' => $this->id]);
            $criteria->addColumnCondition(['type' => $type,]);
            TopicExt::model()->deleteAll($criteria);

            foreach ($this->extIds as $extId) {
                $ext = TopicExt::build($this->id, $extId, $type);
            }

        }

    }

    public function updateLink($in = 'save')
    {
        switch ($in) {
            case 'save':

                break;
            case 'update':
                $criteria = new CDbCriteria();
                $criteria->addColumnCondition(['tid' => $this->id,]);
                SeriesTopic::model()->deleteAll($criteria);
                foreach ($this->sids as $sid)
                {
                    if($model =SeriesTopic::build($sid,$this->id))
                    {
                        $model->save();
                    }
                }

                break;
            case 'delete':
                $criteria = new CDbCriteria();
                $criteria->addColumnCondition(['tid' => $this->id,]);
                TopicExt::model()->deleteAll($criteria);
                SeriesTopic::model()->deleteAll($criteria);
                break;
        }
        return true;
    }

    public function getColumns($type)
    {
        $isVideo = ($type == TopicExt::TYPE_VIDEO);
        return
            $isVideo ? array(
                array('header' => '选择', 'name' => 'choose', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:10%')),
                array('header' => '名称', 'name' => 'name', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:10%')),
                array('header' => '视频封面', 'name' => 'cover', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:20%')),
                array('header' => '创建时间', 'name' => 'time_create', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:30%')),
                array('header' => '操作', 'name' => 'videoOperations', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:20%')),
            ) :
                array(
                    array('header' => '名称', 'name' => 'name', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:10%')),
                    array('header' => '视频数量', 'name' => 'count', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:20%')),
                    array('header' => '创建时间', 'name' => 'time_create', 'value' => array($this, 'colReviseLinkType'), 'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:40%')),
                    array('header' => '操作', 'name' => 'taskOperations', 'value' => array($this, 'colReviseLinkType'),
                        'type' => 'raw', 'headerHtmlOptions' => array('style' => 'width:10%')),
                );

    }

    public function colReviseLinkType($data, $row, $c)
    {
        $name = $c->name;
        switch ($name) {
            case 'choose':
                return CHtml::checkBox('extid',false,['class'=>'video','extid'=>$data->id]);
                break;
            case 'cover':
                $html = '';
                $html .= '<img class="topic-img" src="%s">';
                $html = vsprintf($html, [$data->avetar,]);
                return $html;
                break;
            case 'time_create':
                return date('Y-m-d H:i:s', $data->time_create);
                break;
            case 'videoOperations':
                $params = [];
                $res = '';
                //view
                $params[] = Yii::app()->getController()->createUrl("/manage/video/play", array("id" =>
                    $data->id,));
                $res .= '<a class ="" title="查看" href="%s">查看</a>';
                //add
                $params[] = Yii::app()->getController()->createUrl("add", array("type" => TopicExt::TYPE_VIDEO, "tid" => $this->id, "id" => $data->id,));
                $res .= '<a class ="muiltyAdd " sort="up" title="顺序添加"  href="%s"> 顺序添加</a>';
                $params[] = Yii::app()->getController()->createUrl("add", array("type" => TopicExt::TYPE_VIDEO, "tid" => $this->id, "id" => $data->id,));
                $res .= '<a class ="muiltyAdd  " sort="down"  title="倒序添加"  href="%s"> 倒序添加</a>';
                return vsprintf($res, $params);
            case 'taskOperations':
                $params = [];
                $res = '';
                //edit
                $params[] = Yii::app()->getController()->createUrl("/manage/video/manage", array("Video[task_id]" => $data->id,));
                $res .= '<a class =" " title="查看" href="%s">查看</a>';
                //delete
                $params[] = Yii::app()->getController()->createUrl("add", array("type" => TopicExt::TYPE_TASK, "tid" => $this->id, "id" => $data->id,));
                $res .= '<a class ="add "  title="添加"  href="%s"> 添加</a>';
                return vsprintf($res, $params);
                break;
            case 'count':
                return sizeof($data->Videos);
                break;

        }
        return $data->$name;
    }

    public function getComplateUrl()
    {
        return $_SERVER . $this->url;
    }

    public function getRealVideos($page,$size)
    {
        $videos =[];
        $exts = $this->topicExts;
        $begin =$page*$size;
        $end =($page+1)*$size;
        if($end>$begin)
        {
            foreach ($exts as $ext)
            {
                if($begin<$end)
                {
                    $videos =array_merge($videos,$ext->getVideos($begin, $end));
                }
                $begin += sizeof($videos);
            }
        }
        return $videos;
    }

    public function getRealUrl()
    {
        return $_SERVER['HTTP_HOST'] . $this->url;
    }

    public function sort($exts)
    {
        TopicExt::model()->deleteAll('tid =:tid',[':tid'=>$this->id]);
        $weight = 0;
        foreach ($exts as $ext) {
            $mext= TopicExt::build($this->id,$ext['id'],$ext['type'],$weight);
            $weight++;
            if(!$mext->save())
            {
                return false;
            }
        }
        return true;
    }

}
